<?php
require_once (__DIR__ . "/../inc/functions.php");
require_once (__DIR__ . "/Keywords.php");

class users
{
	static function GetAll()
	{
		$conn = GetConnection();
		$results = $conn->query('SELECT * FROM users');
		$error=$conn->error;
		return $results;
		
	}
	
	static function Get($id)
	{
		$conn = GetConnection();
		$results = $conn->query("SELECT * FROM users WHERE id=$id");
		$row = $results->fetch_assoc();
		$error=$conn->error;
		return $row;
	}

	static function GetUserType($id)
	{
		$row = keywords::Get($id);
		return $row['name'];
	}
	
	static function Insert($row)
	{
		$conn = GetConnection();
		$row2 = EscapeRow($row, $conn);
		$sql = 	"INSERT INTO users (firstName,lastName,username,userType,password) "
			.	"Values ('$row2[firstName]','$row2[lastName]','$row2[username]',$row2[userType],'$row2[password]'); ";
		//echo $sql;
		$conn->query($sql);
		$error = $conn->error;
		$conn->close();
		
		return $error != '' ? array('Server Error' => $error) : true;		
	}
	
	static function Update($row)
	{
		//print_r ($row);	
		$conn = GetConnection();
		$row2 = EscapeRow($row, $conn);
		$sql = 	"UPDATE users "
			.	"Set firstName='$row2[firstName]',lastName='$row2[lastName]',username='$row2[username]',password='$row2[password]',userType=$row2[userType] "
			.	"WHERE id=$row2[id] ";
		//echo $sql;
		$conn->query($sql);
		$error = $conn->error;
		$conn->close();
		
		return $error != '' ? array('Server Error' => $error) : true;		
	}
	
	static function Delete($id)
	{
		$conn = GetConnection();
		$sql = 	"DELETE FROM users "
			.	"WHERE id=$id ";
		//echo $sql;
		$conn->query($sql);
		$error = $conn->error;
		$conn->close();
		
		return $error != '' ? array('Server Error' => $error) : true;				
	}
	static function Validate($row)
	{
		$results=array();
		if(empty($row['firstName'])) $results['firstName'] = 'First name is required';		
		if(empty($row['lastName'])) $results['lastName'] = 'Last name is required';				
		if(empty($row['username'])) $results['username'] = 'Username is required';		
		if(empty($row['password'])) $results['password'] = 'Password is required';		
			
		return count($results) > 0 ? $results : true;
	}
	
}

?>
